<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="/error.jsp"%>
<%@page import="dbexp.model.Table"%>
<%@page import="dbexp.model.db.DbUser"%>
<%@page import="dbexp.connection.DbMetaData"%>
<%
DbUser u = (DbUser)session.getAttribute("USER");
String name = request.getParameter("name");
String schema = request.getParameter("schema");
String tablespace = "USERS";
boolean nowy = (name==null || name.trim().equals("null")) && (schema==null || schema.trim().equals("null"));
String id = schema+"-"+name;
Table t = null;
if(!nowy){
	t = DbMetaData.getTable(u, name.toUpperCase(), schema.toUpperCase());
	name = t.getName();
	schema = t.getSchema();
	tablespace = t.getTableSpace();
}
String save = "Zapisz";
if(nowy){
	name = "Nowa tabela";
	schema=u.getSchemaName();
	save = "Utwórz";
}
%>

<div class="container" style="width:500px">
    <div id="<%=id%>-form"></div>
    <div id="<%=id%>-grid"></div>
</div>
<script type="text/javascript">
try{
var proxy = new Ext.data.HttpProxy({
    api: {
        read : {url:'db/table/column/read.jsp',method:'POST'},
        create :{url:'db/table/column/create.jsp',method:'POST'},
        update: {url:'db/table/column/update.jsp',method:'POST'},
        destroy: {url:'db/table/column/delete.jsp',method:'POST'}
    }
});

var reader = new Ext.data.JsonReader({
    totalProperty: 'total',
    successProperty: 'success',
    idProperty: 'name',
    root: 'data'
},[
   {name:"name",allowBlank: false},
   {name:"dataType", allowBlank: false},
   {name:"size", allowBlank: false},
   {name:"scale", allowBlank: false},
   {name:"nullable",type:'bool'},
   {name:"default", allowBlank: true}
   ]);
//renderer: Ext.util.Format.dateRenderer('m/d/Y')
//stripCharsRe  : /[a-zA-Z0-9]/ig
function change(val){
    if(val > 0){
        return '<span style="color:green;">' + val + '</span>';
    }else if(val < 0){
        return '<span style="color:red;">' + val + '</span>';
    }
    return val;
}
var writer = new Ext.data.JsonWriter({
    encode: true,
    writeAllFields: true
});

var store = new Ext.data.Store({
	baseParams: {name:'<%=name %>', schema:'<%=schema %>',tablespace:'<%=tablespace%>'},
    id: '<%=id%>-store',
    proxy: proxy,
    reader: reader,
    writer: writer,
    autoSave: false,
    batch:true,
    listeners: {
        /*	store::Ext.data.Store,	action::String,	res::Ext.Direct.Transaction,		rs::Record/Record[]	*/
        write : function(store, action, result, res, rs) {
			Ext.Msg.alert('akcja',action);
        },
        exception : function(proxy, type, action, options, res, arg) {
            if (type === 'remote') {
                Ext.Msg.show({
                    title: 'REMOTE EXCEPTION',
                    msg: res.message,
                    icon: Ext.MessageBox.ERROR,
                    buttons: Ext.Msg.OK
                });
            }
        }
    }
});

var textField =  new Ext.form.TextField({allowBlank:false});
var dateField = new Ext.form.DateField({dateFormat:'timestamp',allowBlank:false});
var timeField = new Ext.form.TimeField({format:'m/d/Y H:i:s'});
var typeField=new Ext.form.ComboBox({
    typeAhead: true,
    triggerAction: 'all',
    lazyRender: true,
    mode: 'local',
    width: 50,
    store: new Ext.data.ArrayStore({
        id: 0,
        fields: [
            'typ'
        ],
        data: [['VARCHAR'],[ 'VARCHAR2'], [ 'NUMBER'],['DATE'],['TIMESTAMP'],['CHAR']]
    }),
    valueField: 'typ',
    displayField: 'typ'
});
var numberField = new Ext.form.NumberField({
    allowBlank: true,
    allowNegative: false,
    maxValue: 100000
});

var checkField = new Ext.grid.CheckColumn({
    header: 'Nulls?',
    dataIndex: 'nullable',
    width: 50
 });

// Let's pretend we rendered our grid-columns with meta-data from our ORM framework.
var tableColumns = new Ext.grid.ColumnModel( [
    {header: "Nazwa", width: 90, dataIndex: 'name', editor: textField},
    {header: "Typ", width: 80, dataIndex: 'dataType', editor: typeField},
    {header: "Wielkość", width: 80, dataIndex: 'size', editor: numberField},
    {header: "Skala", width: 80, dataIndex: 'scale', editor: numberField},
    checkField,
    {header: "Domyślnie", width: 80, dataIndex: 'default', editor: textField}
]);
tableColumns.defaultSortable = true;
store.load();

TableColumnsGrid = Ext.extend(Ext.grid.EditorGridPanel, {
    renderTo: '<%=id%>-grid',
    iconCls: 'silk-grid',
    frame: true,
    border:false,
    title: 'Kolumny',
    height: 300,
    width: 900,
    style: 'margin-top: 10px',

    initComponent : function() {
        this.viewConfig = {
            forceFit: false
        };
        this.relayEvents(this.store, ['destroy', 'save', 'update']);
        this.tbar = this.buildTopToolbar();
        TableColumnsGrid.superclass.initComponent.call(this);
    },
    buildTopToolbar : function() {
        return [{
            text: 'Dodaj',
            iconCls: 'silk-add',
            handler: this.onAdd,
            scope: this
        }, '-', {
            text: 'Usuń',
            iconCls: 'silk-delete',
            handler: this.onDelete,
            scope: this
        }, '-'];
    },
    onAdd : function(btn, ev) {
        var u = new this.store.recordType({
            name : '',
            dataType: 'VARCHAR2',
            size : '10',
            scale:'0',
            nullable:false,
            default:''
        });
        this.stopEditing();
        this.store.insert(0, u);
        this.startEditing(0, 0);
    },
    onDelete : function(btn, ev) {
        var index = this.getSelectionModel().getSelectedCell();
        if (!index) {
            return false;
        }
        var rec = this.store.getAt(index[0]);
        this.store.remove(rec);
    },
   	onSuccess:function(action) {
   		obj = Ext.util.JSON.decode(action.response.responseText);
        var root = Ext.getCmp('api-tree').getRootNode();
        catNode={};
    	if( (catNode=root.findChild("t","32"))!=null){
    		catNode.reload();
    	}
    },
    onFailure:function(action) {
    		this.showError(action.response.responseText);
    },
    showError:function(msg) {
    	obj = Ext.util.JSON.decode(msg);
    	 title = obj.error.title||'Error';
    	 Ext.Msg.show({
    		title:title,
    	 	msg:obj.error.msg||obj.error,
    	 	modal:true,
    	 	icon:Ext.Msg.ERROR,
    	 	buttons:Ext.Msg.OK
    	 });
    }
});
var tableGrid = new TableColumnsGrid({
    renderTo: '<%=id%>-grid',
    store: store,
    defaults: {
        sortable: true           
    },
    cm : tableColumns,
    plugins:checkField,
    listeners: {
        rowclick: function(g, index, ev) {
            var rec = g.store.getAt(index);
        },
        destroy : function() {
        	tableForm.getForm().reset();
        }
    }
});

TableForm = Ext.extend(Ext.form.FormPanel, {
    renderTo: '<%=id%>-form',
    id:'<%=id%>-table-form',
    frame: true,
    frame: true,
    width: 900,
    url:'db/table/table.jsp',
    defaultType: 'textfield',
    defaults: {
        anchor: '100%'
    },
    initComponent : function() {
    	 var config={
    	        	defaultType: 'textfield',
    	        	defaults: {
    	            	anchor: '100%'
    	       		},
    	       		defaultType: 'textfield',
    	monitorValid:true,
       	items: [
       	         {
        	            xtype:'tabpanel',
           	            activeTab: 0,
           	            resizeTabs: true,
           	            animScroll:false,
           	         	<%if(!nowy){%>
           	           	listeners: {
           	           		tabchange: function(tabPanel,newTab){
			 					var thisObj = newTab.getUpdater();
			 					if(thisObj && newTab.id=='<%=id%>-table-data'){
				 					Ext.getCmp('<%=id%>-save').hide();
				 					Ext.getCmp('<%=id%>-refresh').hide();
				 					thisObj.update({url:'output/table/table-data.jsp', params:{name:'<%=name %>', schema:'<%=schema %>'},method:'POST',scripts: true });
			 					}else{
			 						Ext.getCmp('<%=id%>-save').show();
				 					Ext.getCmp('<%=id%>-refresh').show();
				 				}
		  					}
	    				},
	    				<%}%>
       					minTabWidth: 135,
        				tabWidth: 135,
        				items:[
               				{
										title:'Ogólne',
										id:'<%=id%>-table-main',
										layout:'form',
										frame:true,
										bodyStyle:'padding:10px',height:450,
										defaultType: 'textfield',
								        	defaults: {
							            	anchor: '95%'
						       			},
				           	            items:[
							       	    	{fieldLabel: 'Nazwa', name: 'name', allowBlank: false,value:'<%=name %>'<%=(nowy)?"":",readOnly:true,disabled:true"%>},
       	        							<%=(nowy)?"combo({emptyText:'"+schema+"'}),":"{fieldLabel:'Schemat',name:'schema',allowBlank:false,value:'"+schema+"',readOnly:true,disabled:true},"%>
       	        							<%=(nowy)?"comboTS({emptyText:'"+tablespace+"'}),":"{fieldLabel:'Przestrzeń tabel',name:'tablespace',allowBlank:false,value:'"+tablespace+"',readOnly:true,disabled:true},"%>
       	        							tableGrid
       	        						]
       	        			}
               			 <%if(!nowy){%>
       	        			,{
								title:'Dane',
								id:'<%=id%>-table-data',
								layout:'fit',
								height:350,
								border:false,
								autoScroll:true
	        			}
    	        		<%}%>	
       	        		]
       	         }
             ]
    };
		Ext.apply(this, Ext.apply(this.initialConfig, config));
		TableForm.superclass.initComponent.apply(this, arguments);
    },
    buttons:[{
        	id:'<%=id%>-save',
	    	text: 'Zapisz',
	    	iconCls: 'icon-save',
	    	scope: this,
	    	handler:this.submit
   	},{
   		text: 'Odśwież',
   		id:'<%=id%>-refresh',
   		tooltip:'Zaczytuje obiekt ponownie z bazy danych',
   		scope: this,
        handler: function(btn, ev){
        	this.getForm().load({url:'db/table/table.jsp',params:{name:'<%=name %>', schema:'<%=schema %>',action:'get'},method:'POST'});
        	tableGrid.store.load();
    	}
    }],
	onRender:function() {
    	TableForm.superclass.onRender.apply(this, arguments);
	    this.getForm().waitMsgTarget = this.getEl();
    },
	onLoadClick:function() {
    	this.load({
	    	url:this.url
	    	,waitMsg:'Ładowanie...'
	    	 ,params:{name:'${name}',schema:'${schema}',action:'get'},method:'POST'
    	});
    },
    submit:function() {
        rs = tableGrid.store.getRange();
        if(rs && rs.length>0){
            for(var i=0;i<rs.length;i++){
				if(rs[i].phantom && !rs[i].isValid()){
					Ext.MessageBox.show({
				           title: 'Błędne dane',
				           msg: 'Wypełnij poprawnie wszystkie pola!',
				           buttons: Ext.MessageBox.OK,
				           icon: Ext.MessageBox.INFO
				       });
					return;
				}
            }
        }
	    	tableGrid.store.save();
	        var root = Ext.getCmp('api-tree').getRootNode();
	        var category_node = root.findChild("t","513").reload();
	   		<%if(nowy){%>
	   		Ext.Msg.alert('DbExplorer','Z powodzeniem utworzono nową tabelę');
			var w = Ext.getCmp('create-window');
			if(w){
				w.close();
			}
		<%}%>
   	}
});

Ext.onReady(function() {
    Ext.form.Field.prototype.msgTarget = 'side';
    var tableForm = new TableForm({
        renderTo: '<%=id%>-form'
    });

});
}catch(e){alert(e);}
</script>